<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import {
  deleteMemberOrderAPI,
  getMemberOrderAPI,
  getMemberOrderCancelByIdAPI,
  getMemberOrderConsignmentByIdAPI,
  getPayMockAPI,
  getPayWxPayMiniPayAPI,
  putMemberOrderReceiptByIdAPI,
} from '@/services/order';
import type { OrderItem, OrderListParams } from '@/types/order';
import { ref } from 'vue';
import { OrderState, orderStateList } from '@/services/constants';
import PageSkeleton from './PageSkeleton.vue';

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();

// 定义props
const props = defineProps<{
  orderState: number;
}>();

// 弹出层组件
const popup = ref<UniHelper.UniPopupInstance>();
// 取消原因列表
const reasonList = ref([
  '商品无货',
  '不想要了',
  '商品信息填错了',
  '地址信息填写错误',
  '商品降价',
  '其它',
]);
// 订单取消原因
const reason = ref('');

// 请求参数
const queryParams: Required<OrderListParams> = {
  page: 1,
  pageSize: 5,
  orderState: props.orderState,
};

// 获取订单列表
const isLoading = ref(true);
const orderList = ref<OrderItem[]>([]);
const getMemberOrderData = async () => {
  if (finish.value) {
    return uni.showToast({
      icon: 'none',
      title: '没有更多了',
    });
  }
  const res = await getMemberOrderAPI(queryParams);
  orderList.value.push(...res.result.items);
  // 当前页码是否小于总页数
  if (queryParams.page < res.result.pages) {
    queryParams.page++;
  } else {
    finish.value = true;
  }
};

// 触底加载更多
const finish = ref(false);
const onScrolltolower = () => {
  getMemberOrderData();
};

onLoad(async () => {
  isLoading.value = true;
  await getMemberOrderData();
  isLoading.value = false;
});

// 下拉刷新
const isPull = ref(false);
const onRefresherrefresh = async () => {
  isPull.value = true;
  await resetData();
  isPull.value = false;
};

const resetData = async () => {
  // 重新请求刷新数据
  queryParams.page = 1;
  finish.value = false;
  const res = await getMemberOrderAPI(queryParams);
  orderList.value = res.result.items;
  // 当前页码是否小于总页数
  if (queryParams.page < res.result.pages) {
    queryParams.page++;
  } else {
    finish.value = true;
  }
};

// 删除订单
const onOrderDelete = async (id: string) => {
  // 二次确认弹窗
  uni.showModal({
    content: '确认删除该订单吗？',
    success: async (success) => {
      if (success.confirm) {
        await deleteMemberOrderAPI({ ids: [id] });
        // 重新请求刷新数据
        resetData();
      }
    },
  });
};

// 订单支付
const onOrderPay = async (id: string) => {
  if (import.meta.env.DEV) {
    // 开发环境模拟支付
    await getPayMockAPI({ orderId: id });
  } else {
    // 正式环境微信支付
    const res = await getPayWxPayMiniPayAPI({ orderId: id });
    wx.requestPayment(res.result);
  }
  // 成功提示
  uni.showToast({ title: '支付成功' });
  // 更新订单状态
  const order = orderList.value.find((v) => v.id === id);
  order!.orderState = OrderState.DaiFaHuo;
};

// 是否为开发环境
const isDev = import.meta.env.DEV;
// 模拟发货
const onOrderSend = async (id: string) => {
  if (isDev) {
    await getMemberOrderConsignmentByIdAPI(id);
    uni.showToast({ icon: 'success', title: '模拟发货成功' });
    // 更新订单状态
    const order = orderList.value.find((v) => v.id === id);
    order!.orderState = OrderState.DaiShouHuo;
  }
};

// 确认收货
const onOrderConfirm = (id: string) => {
  // 二次确认弹窗
  uni.showModal({
    content: '为保障您的权益，请收到货并确认无误后，再确认收货',
    success: async (success) => {
      if (success.confirm) {
        await putMemberOrderReceiptByIdAPI(id);
        // 更新订单状态
        const order = orderList.value.find((v) => v.id === id);
        order!.orderState = OrderState.DaiPingJia;
      }
    },
  });
};

// 取消订单
const cancelOrderId = ref('');
const onCancel = (id: string) => {
  popup.value!.open?.();
  cancelOrderId.value = id;
};
const onOrderCancel = async () => {
  await getMemberOrderCancelByIdAPI(cancelOrderId.value, { cancelReason: reason.value });
  // 更新订单状态
  const order = orderList.value.find((v) => v.id === cancelOrderId.value);
  order!.orderState = OrderState.YiQuXiao;
  uni.showToast({ icon: 'success', title: '取消订单成功' });
  popup.value!.close!();
};
</script>
<template>
  <scroll-view
    v-if="!isLoading"
    scroll-y
    class="orders"
    @scrolltolower="onScrolltolower"
    :refresher-enabled="true"
    :refresher-triggered="isPull"
    @refresherrefresh="onRefresherrefresh"
  >
    <view class="card" v-for="order in orderList" :key="order.id">
      <!-- 订单信息 -->
      <view class="status">
        <text class="date">{{ order.createTime }}</text>
        <!-- 订单状态文字 -->
        <text>{{ orderStateList[order.orderState].text }}</text>
        <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
        <text
          v-if="order.orderState >= OrderState.DaiPingJia"
          class="icon-delete"
          @tap="onOrderDelete(order.id)"
        ></text>
      </view>
      <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
      <navigator
        v-for="sku in order.skus"
        :key="sku.id"
        class="goods"
        :url="`/pagesOrder/detail/detail?id=${order.id}`"
        hover-class="none"
      >
        <view class="cover">
          <image mode="aspectFit" :src="sku.image"></image>
        </view>
        <view class="meta">
          <view class="name ellipsis">{{ sku.name }}</view>
          <view class="type">{{ sku.attrsText }}</view>
        </view>
      </navigator>
      <!-- 支付信息 -->
      <view class="payment">
        <text class="quantity">共{{ order.totalNum }}件商品</text>
        <text>实付</text>
        <text class="amount"> <text class="symbol">¥</text>{{ order.payMoney }}</text>
      </view>
      <!-- 订单操作按钮 -->
      <view class="action">
        <!-- 待付款状态：显示去支付按钮 展示支付按钮 -->
        <template v-if="order.orderState === OrderState.DaiFuKuan">
          <view class="button" @tap="onCancel(order.id)"> 取消订单 </view>
          <view class="button primary" @tap="onOrderPay(order.id)">去支付</view>
        </template>
        <template v-else>
          <navigator
            class="button secondary"
            :url="`/pagesOrder/create/create?orderId=${order.id}`"
            hover-class="none"
          >
            再次购买
          </navigator>
          <!-- 待发货状态且是开发环境: 展示模拟发货 -->
          <view
            v-if="isDev && order.orderState === OrderState.DaiFaHuo"
            class="button"
            @tap="onOrderSend(order.id)"
          >
            模拟发货
          </view>
          <!-- 待收货状态: 展示确认收货 -->
          <view
            v-if="order.orderState === OrderState.DaiShouHuo"
            class="button primary"
            @tap="onOrderConfirm(order.id)"
          >
            确认收货
          </view>
        </template>
      </view>
    </view>
    <!-- 底部提示文字 -->
    <view class="loading-text" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      {{ finish ? '没有更多数据~' : '正在加载...' }}
    </view>
  </scroll-view>

  <PageSkeleton v-else />

  <!-- 取消订单弹窗 -->
  <uni-popup ref="popup" type="bottom" background-color="#fff">
    <view class="popup-root">
      <view class="title">订单取消</view>
      <view class="description">
        <view class="tips">请选择取消订单的原因：</view>
        <view class="cell" v-for="item in reasonList" :key="item" @tap="reason = item">
          <text class="text">{{ item }}</text>
          <text class="icon" :class="{ checked: item === reason }"></text>
        </view>
      </view>
      <view class="footer">
        <view class="button" @tap="popup?.close?.()">取消</view>
        <view class="button primary" @tap="onOrderCancel">确认</view>
      </view>
    </view>
  </uni-popup>
</template>
<style lang="scss">
.orders {
  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .goods {
    display: flex;
    margin-bottom: 20rpx;

    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 10rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;

    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

    .amount {
      color: #444;
      margin-left: 6rpx;
    }

    .symbol {
      font-size: 20rpx;
    }
  }

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .button {
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ccc;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #27ba9b;
      border-color: #27ba9b;
    }

    .primary {
      color: #fff;
      background-color: #27ba9b;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}

.popup-root {
  padding: 30rpx 30rpx 0;
  border-radius: 10rpx 10rpx 0 0;
  overflow: hidden;

  .title {
    font-size: 30rpx;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .description {
    font-size: 28rpx;
    padding: 0 20rpx;

    .tips {
      color: #444;
      margin-bottom: 12rpx;
    }

    .cell {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15rpx 0;
      color: #666;
    }

    .icon::before {
      content: '\e6cd';
      font-family: 'erabbit' !important;
      font-size: 38rpx;
      color: #999;
    }

    .icon.checked::before {
      content: '\e6cc';
      font-size: 38rpx;
      color: #27ba9b;
    }
  }

  .footer {
    display: flex;
    justify-content: space-between;
    padding: 30rpx 0 40rpx;
    font-size: 28rpx;
    color: #444;

    .button {
      flex: 1;
      height: 72rpx;
      text-align: center;
      line-height: 72rpx;
      margin: 0 20rpx;
      color: #444;
      border-radius: 72rpx;
      border: 1rpx solid #ccc;
    }

    .primary {
      color: #fff;
      background-color: #27ba9b;
      border: none;
    }
  }
}
</style>
